package com.ruoyi.web.controller.system;

import cn.hutool.core.bean.BeanUtil;
import com.angel.mongodb.utils.Wraps;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.core.service.impl.BaseService;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.web.viewObject.SysRoleVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @description: 角色信息
 * @author: gankench@gmail.com
 * @time: 4/10/21 8:30 PM
 */
@RestController
@RequestMapping("/system/role")
public class SysRoleController extends BaseController {
    @Autowired
    private BaseService baseService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysPermissionService permissionService;


    @PreAuthorize("@ss.hasPermi('system:role:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysRoleVo role) {
        SysRole sysRole = BeanUtil.copyProperties(role, SysRole.class);
        Query query = Wraps.buildBasePageQuery(sysRole, TableSupport.buildPageRequest());
        List<SysRoleVo> list = baseService.findPage(query, SysRole.class)
                .stream()
                .map(e -> BeanUtil.copyProperties(e, SysRoleVo.class))
                .collect(Collectors.toList());
        return getDataTable(list);
    }

    @Log(title = "角色管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:role:export')")
    @GetMapping("/export")
    public AjaxResult export(SysRoleVo role) {
        List<SysRole> list = baseService.findListByQuery(Wraps.buildBaseQuery(role), SysRole.class);
        ExcelUtil<SysRole> util = new ExcelUtil<SysRole>(SysRole.class);
        return util.exportExcel(list, "角色数据");
    }

    /**
     * 根据角色编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:role:query')")
    @GetMapping(value = "/{roleId}")
    public AjaxResult getInfo(@PathVariable String roleId) {
        return AjaxResult.success(baseService.findById(roleId, SysRole.class));
    }

    /**
     * 新增角色
     */
    @PreAuthorize("@ss.hasPermi('system:role:add')")
    @Log(title = "角色管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysRoleVo role) {
        SysRole sysRole = BeanUtil.copyProperties(role, SysRole.class);
        if (UserConstants.NOT_UNIQUE.equals(baseService.findCountByQuery(Wraps.andWrapper(sysRole), SysRole.class))) {
            return AjaxResult.error("新增角色'" + role.getRoleName() + "'失败，角色名称已存在");
        } else if (UserConstants.NOT_UNIQUE.equals(baseService.findCountByQuery(Wraps.andWrapper(sysRole), SysRole.class))) {
            return AjaxResult.error("新增角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        sysRole.setCreateBy(SecurityUtils.getUsername());
        baseService.save(sysRole);
        return toAjax(true);

    }

    /**
     * 修改保存角色
     */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysRoleVo role) {
        SysRole sysRole = BeanUtil.copyProperties(role, SysRole.class);
        baseService.checkRoleAllowed(sysRole);
        if (baseService.findCountByQuery(Wraps.andWrapper().eq(SysRole::getRoleName, role.getRoleName()), SysRole.class).intValue() > 0) {
            return AjaxResult.error("修改角色'" + role.getRoleName() + "'失败，角色名称已存在");
        } else if (baseService.findCountByQuery(Wraps.andWrapper().eq(SysRole::getRoleKey, role.getRoleKey()), SysRole.class).intValue() > 0) {
            return AjaxResult.error("修改角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        sysRole.setUpdateBy(SecurityUtils.getUsername());
        try {
            baseService.updateRole(sysRole);
            // 更新缓存用户权限
            LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
            if (StringUtils.isNotNull(loginUser.getUser()) && !loginUser.getUser().isAdmin()) {
                loginUser.setPermissions(permissionService.getMenuPermission(loginUser.getUser()));
                loginUser.setUser(baseService.findOneByQuery(Wraps.andWrapper().eq(SysUser::getUserName, loginUser.getUser().getUserName()), SysUser.class));
                tokenService.setLoginUser(loginUser);
            }
            return AjaxResult.success();
        } catch (Exception e) {
            return AjaxResult.error("修改角色'" + role.getRoleName() + "'失败，请联系管理员");
        }

    }

    /**
     * 修改保存数据权限
     */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping("/dataScope")
    public AjaxResult dataScope(@RequestBody SysRoleVo role) {
        SysRole sysRole = BeanUtil.copyProperties(role, SysRole.class);
        baseService.checkRoleAllowed(sysRole);
        baseService.authDataScope(sysRole);
        return toAjax(true);
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysRoleVo role) {
        SysRole sysRole = BeanUtil.copyProperties(role, SysRole.class);
        baseService.checkRoleAllowed(sysRole);
        sysRole.setUpdateBy(SecurityUtils.getUsername());
        baseService.updateById(sysRole);
        return toAjax(1);
    }

    /**
     * 删除角色
     */
    @PreAuthorize("@ss.hasPermi('system:role:remove')")
    @Log(title = "角色管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{roleIds}")
    public AjaxResult remove(@PathVariable List<String> roleIds) {
        return toAjax(baseService.deleteByIds(roleIds, SysRole.class).intValue());
    }

    /**
     * 获取角色选择框列表
     */
    @PreAuthorize("@ss.hasPermi('system:role:query')")
    @GetMapping("/optionselect")
    public AjaxResult optionselect() {
        return AjaxResult.success(baseService.findAll(SysRole.class));
    }


}
